package com.heima.comment.service.Impl;

import com.heima.comment.pojos.ApComment;
import com.heima.comment.service.CommentHotService;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CommentHotServiceImpl implements CommentHotService {

    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 处理热点评论
     *
     * @param entryId
     * @param apComment
     */
    @Override
    @Async  //异步执行
    public void hotCommentExecutor(Long entryId, ApComment apComment) {
        //查询当前文章热点评论的所有数据
        List<ApComment> commentHotList = mongoTemplate.find(Query.query(Criteria
                        .where("entryId").is(entryId)
                        .and("type").is(0)
                        .and("flag").is(1))
                        .with(Sort.by(Sort.Order.desc("likes")))
                , ApComment.class);

        //如果没有热点数据，则直接新增热点评论
        if (commentHotList == null || commentHotList.size() < 5) {
            apComment.setFlag((short) 1);
            mongoTemplate.save(apComment);
            return;
        }

        //判断当前评论的点赞数是否大于热点评论中的最小点赞数
        if (commentHotList != null && commentHotList.size() > 0) {
            ApComment lastcomment = commentHotList.get(commentHotList.size() - 1);

            if (apComment.getLikes() > lastcomment.getLikes()) {
                if (commentHotList.size() >= 5) {
                    lastcomment.setFlag((short) 0);
                    mongoTemplate.save(lastcomment);
                }

            }

            apComment.setFlag((short) 1);
            mongoTemplate.save(apComment);

        }
    }
}
